package com.sun.log;

import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import lombok.Data;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

/**
 * log4j提供的输出器实现⾃Appender接⼝，要⾃定义appender输出到MongoDB，只需要继承AppenderSkeleton类
 * @author Administrator
 */
public class MongoAppender extends AppenderSkeleton {

    /**
     * mongodb的连接客户端
     */
    private MongoClient mongoClient;
    /**
     * 记录⽇志的数据库
     */
    private MongoDatabase mongoDatabase;
    /**
     * 记录⽇志的集合
     */
    private MongoCollection<BasicDBObject> logsCollection;

    /**
     * 连接mongodb的串
     */
    private String connectionUrl;
    /**
     * 数据库名
     */
    private String databaseName;
    /**
     * 集合名
     */
    private String collectionName;

    @Override
    protected void append(LoggingEvent loggingEvent) {
        if(null==mongoDatabase){
            MongoClientURI connectionString = new MongoClientURI(connectionUrl);
            mongoClient=new MongoClient(connectionString);
            mongoDatabase=mongoClient.getDatabase(databaseName);
            logsCollection=mongoDatabase.getCollection(collectionName,BasicDBObject.class);
        }
        // LoggingEvent提供getMessage()函数来获取⽇志消息
        logsCollection.insertOne((BasicDBObject)loggingEvent.getMessage());
    }

    @Override
    public void close() {
        if(mongoClient != null){
            mongoClient.close();
        }
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    public String getConnectionUrl() {
        return connectionUrl;
    }

    public void setConnectionUrl(String connectionUrl) {
        this.connectionUrl = connectionUrl;
    }

    public String getDatabaseName() {
        return databaseName;
    }

    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }

    public String getCollectionName() {
        return collectionName;
    }

    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }
}
